from django.shortcuts import render_to_response
from django.template import RequestContext, Context

from ktit.shm.models import Department, Employee



def recursive_get_department_list(department, level):
    res = []
    for di in department:
        item = {"id":di.id,"name":di.name,"parent":di.parent,"level":level,"csslevel":level*24,}
        department_set = di.department_set.all()
        item["child_present"] = department_set
        res.append(item)
        subdepartments=recursive_get_department_list(department_set, level+1)
        res.extend(subdepartments)
    return res



def create_department_tree():
    d = Department.objects.select_related().filter(parent=None)
    return recursive_get_department_list(d, 0)


def index(request): 
    departments = create_department_tree()
    
    
    context = Context({
      'departments' : departments,
    })
    return render_to_response('shm/index.html', context)


def dep_list(request, department_id): 
    departments = create_department_tree()
    department = Department.objects.get(id=department_id)
    phone = department.phone.all()  #Phone.objects.get()
    employee = Employee.objects.filter(department=department_id)
    
    context = Context({
      'departments' : departments,
      'department': department,
      'phone': phone,
      'employee':employee,
    })
    return render_to_response('shm/department_list.html', context)